package com.demo.juc.inter;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 资源类:
 * 高内聚、低耦合
 * 判断、干活、通知
 * 模板：

 *     private Lock lock = new ReentrantLock();
 *     private Condition condition = lock.newCondition();
 *
 *     public void m() throws InterruptedException {
 *         lock.lock();
 *         try {
 *             while () {
 *                 condition.await();
 *             }
 *             //to do
 *             condition.signalAll();
 *         } finally {
 *             lock.unlock();
 *         }
 *
 *     }
 */
class ScoreLock {

    private int number = 0;

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void increase() throws InterruptedException {
        lock.lock();
        try {
            while (number != 0) {
                //this.wait();
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + ":\t" + number);
            //this.notifyAll();
            condition.signalAll();
        }finally {
            lock.unlock();
        }

    }

    public void decrease() throws InterruptedException {
        lock.lock();
        try {
            while (number == 0) {
                //this.wait();
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + ":\t" + number);
            //this.notifyAll();
            condition.signalAll();
        } finally {
            lock.unlock();
        }

    }

}
